package com.cmdi.mq.feign;

import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.cmdi.mq.constant.CodeConstants;
import com.cmdi.mq.domain.R;
import com.cmdi.mq.domain.SysUserLog;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @Description: Feign容错处理类
 * @Author: gaozb
 */
@Configuration
@Slf4j
public class RemoteLogServiceFeignClientFallBackFactory implements FallbackFactory<RemoteLogServiceFeignClient> {
    @Override
    public RemoteLogServiceFeignClient create(Throwable throwable) {
        return new RemoteLogServiceFeignClient() {
            @Override
            public ResponseEntity<R> saveLog(SysUserLog sysUserLog, String token) {
                log.error(CodeConstants.ERROR_REASON_PREFIX, throwable);
                String msg = null;
                if(throwable instanceof FlowException) {
                    msg = CodeConstants.FLOW_EXCEPTION_PREFIX + throwable.getMessage();
                } else if(throwable instanceof DegradeException) {
                    msg = CodeConstants.DEGRADE_EXCEPTION_PREFIX + throwable.getMessage();
                } else {
                    //throwable.getCause() instanceof ClientException
                    msg = CodeConstants.OTHER_EXCEPTION_PREFIX + throwable.getMessage();;
                }
                return new ResponseEntity<R>(R.fail(-1, msg), HttpStatus.NOT_ACCEPTABLE);
            }
        };
    }
}